package pers.hl.common.ui.widget

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.ViewConfiguration
import androidx.recyclerview.widget.RecyclerView
import kotlin.math.abs

/**
 * 内部拦截法，针对两个横向嵌套滑动的View
 */
class InternalHorRecyclerView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : RecyclerView(context, attrs, defStyleAttr) {

    private var touchSlop: Int = 0
    private var lastX: Float = 0.0f
    private var lastY: Float = 0.0f

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (touchSlop == 0) {
            touchSlop = ViewConfiguration.get(context).scaledTouchSlop
            Log.e("touchSlop", touchSlop.toString())
        }
        ev?.let {
            val x = it.x
            val y = it.y
            when (it.action) {
                MotionEvent.ACTION_DOWN -> {
                    lastX = x
                    lastY = y
                    // 禁止parent拦截down事件
                    parent.requestDisallowInterceptTouchEvent(true)
                }
                MotionEvent.ACTION_MOVE -> {
                    // 根据需求条件来决定是否让Parent View拦截事件。
                    parent.requestDisallowInterceptTouchEvent(disallowParentInterceptTouchEvent(it))
                }
                MotionEvent.ACTION_UP,
                MotionEvent.ACTION_CANCEL -> {
                    parent.requestDisallowInterceptTouchEvent(false)
                }
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    /**
     * 此处判断，是左右滑动并且横向滑动大于纵向滑动，就禁止外层处理
     */
    private fun disallowParentInterceptTouchEvent(ev: MotionEvent): Boolean {
        val deltaX = abs(ev.x - lastX).toInt()
        val deltaY = abs(ev.y - lastY).toInt()
        return deltaY in (touchSlop + 1) until deltaX
    }
}